package org.dromara.assets.config;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.dromara.assets.domain.AssetsTradePlan;
import org.dromara.assets.mapper.AssetsTradePlanMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.StateMachineContext;
import org.springframework.statemachine.action.Action;
import org.springframework.statemachine.config.EnableStateMachineFactory;
import org.springframework.statemachine.config.StateMachineConfigurerAdapter;
import org.springframework.statemachine.config.StateMachineFactory;
import org.springframework.statemachine.config.builders.StateMachineStateConfigurer;
import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;
import org.springframework.statemachine.guard.Guard;
import org.springframework.statemachine.support.DefaultStateMachineContext;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.EnumSet;
import java.util.List;

@Slf4j
@Configuration
@EnableScheduling
public class TradeStateMachineTask {

    @Autowired
    private AssetsTradePlanMapper assetsTradePlanMapper;

    @Resource
    private StateMachine<TradePlanStatusEnum, TradePlanStatusEventEnum> tradePlanStatusMachine;

    // 定时任务：每30秒处理
   // @Scheduled(fixedRate = 30000)
    public void processTradePlans() {
        log.info("start processTradePlans");
        List<AssetsTradePlan> plans = assetsTradePlanMapper.selectList(new LambdaQueryWrapper<AssetsTradePlan>());
        tradePlanStatusMachine.stop();
        for (AssetsTradePlan plan : plans) {
            log.info("start plan: {}", plan.getId());
            // 从数据库加载初始状态并重置状态机
            TradePlanStatusEnum initialState = TradePlanStatusEnum.fromValue(plan.getState());
            StateMachineContext<TradePlanStatusEnum, TradePlanStatusEventEnum> context = new DefaultStateMachineContext<>(initialState, null, null, null);
            tradePlanStatusMachine.getStateMachineAccessor().doWithAllRegions(accessor -> {
                try {
                    accessor.resetStateMachine(context); // 重置到DB状态
                } catch (Exception e) {
                    throw new RuntimeException("Failed to reset state machine", e);
                }
            });
            tradePlanStatusMachine.start();
            if (plan.getState() == 20) continue; // 已完成跳过
            tradePlanStatusMachine.getExtendedState().getVariables().put("tradePlan", plan);
            try {
                TradePlanStatusEnum current = plan.getStateEnum();
                TradePlanStatusEventEnum tradePlanStatusEventEnum = triggerEventByState(current);
                log.info("send Event,planId:{}, event:{}", plan.getId(), tradePlanStatusEventEnum);
                // 将这个对象封装成为一个message
                Message<TradePlanStatusEventEnum> message = MessageBuilder
                        .withPayload(tradePlanStatusEventEnum)
                        //.setHeader("order", entity)
                        .build();
                tradePlanStatusMachine.sendEvent(message);
                log.info("process end,planId:{}", plan.getId());
            } catch (Exception e) {
                log.error("", e);
                plan.setRemarks(plan.getRemarks() + "; Error: " + e.getMessage());
                //assetsTradePlanMapper.update(plan);
            }
        }
    }

    private TradePlanStatusEventEnum triggerEventByState(TradePlanStatusEnum state) {
        switch (state) {
            case STATE_1:
                return TradePlanStatusEventEnum.CHECK_PRICE;
            case STATE_2:
                // 同步处理赎回和交换
                return planNeedsRedeem() ? TradePlanStatusEventEnum.REDEEM : TradePlanStatusEventEnum.SWAP; //
            // 简化，实际可链式
            case STATE_3:
                return TradePlanStatusEventEnum.PLACE_ORDER;
            case STATE_4:
                return TradePlanStatusEventEnum.CHECK_TRANSACTION;
            case STATE_5:
                return TradePlanStatusEventEnum.ALERT;
            case STATE_6:
                return TradePlanStatusEventEnum.NOTIFY;
            default:
                return null;
        }
    }

    private boolean planNeedsRedeem() {
        // 示例：从上下文中获取
        return false; // 实际从plan判断
    }
}